﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Infancy.Core.Validation {
    /// <summary>
    /// 数字范围验证
    /// </summary>
    [AttributeUsage(AttributeTargets.Property)]
    public class RangeAttribute : ValidateAttributeBase {
        public int Min { get; set; }

        public int Max { get; set; }

        public RangeAttribute() {
            Min = Int32.MinValue;
            Max = Int32.MaxValue;
        }

        /// <summary>
        /// 默认构造函数
        /// </summary>
        /// <param name="min">范围的最小值(可以等于)</param>
        /// <param name="max">范围的最大值(可以等于)</param>
        /// <param name="message">错误信息,占位符信息:{0}代表属性名,{1}代表Mix值,{2}代表Max值</param>
        public RangeAttribute(int min, int max, string message) {
            Min = min;
            Max = max;
            Message = message;
        }

        public override ValidatedResult Execute(ValidateContext context) {
            int value;
            Dictionary<string, string> errers = new Dictionary<string, string>();
            if (!Int32.TryParse(context.Value.ToString(), out value)) {
                errers.Add(context.Name,
                    String.Format(Message, context.Name, Min, Max));
            } else {
                if (value < Min || value > Max) {
                    errers.Add(context.Name,
                    String.Format(Message, context.Name, Min, Max));
                }
            }
            return new ValidatedResult(errers.Count > 0 ? false : true, errers);
        }
    }
}
